import base64
import urllib
import requests

API_KEY = "自己的API"
SECRET_KEY = "自己的API"

def main():
        
    url = "https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice?access_token=" + get_access_token()
    
    # pdf_file 可以通过 get_file_content_as_base64("C:\fakepath\000E98EC284BD48FFF240DBB586DC03048436C310EC6FB6508A8B92AB8F37AED.pdf",True) 方法获取
    pdf_file = get_file_content_as_base64("36311.pdf",True)
    payload='pdf_file='+pdf_file+'&seal_tag=false'
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))
    
    # print(response.text)
    # 把json转换为object
    import json
    source_date = json.loads(response.text)
    # print(source_date['log_id']) #测试是否转换成功
    '''
    # 获取数据，当前需要获取 货物名称、数量、单价、金额、税额、销售方单位名称、总金额、大写总金额
    #获取货物名称对象的长度
    source_date_CommodityName_len= len(source_date['words_result']['CommodityName'])  
    for i in range(0,source_date_CommodityName_len,1):
        #成功获取商品名称
        print('商品名称'+source_date['words_result']['CommodityName'][i]['word']+'\n')
    #获取货物数量的对象长度
    source_date_CommodityNum_len = len(source_date['words_result']['CommodityNum'])
    for i in range(0,source_date_CommodityNum_len,1):
        # 获取每个商品的数量
        print('商品数量'+source_date['words_result']['CommodityNum'][i]['word']+'\n')
    #获取单价的对象长度
    source_date_CommodityPrice_len = len(source_date['words_result']['CommodityPrice'])
    for i in range(0,source_date_CommodityPrice_len,1):
        # 获取每个单价
        print('商品单价'+source_date['words_result']['CommodityPrice'][i]['word']+'\n')
    #获取 金额对象的长度
    source_date_CommodityAmount_len = len(source_date['words_result']['CommodityAmount'])
    for i in range(0,source_date_CommodityAmount_len,1):
        # 获取每个金额
        print('商品金额'+source_date['words_result']['CommodityAmount'][i]['word']+'\n')
    #获取税额的对象长度
    source_date_CommodityTax_len = len(source_date['words_result']['CommodityTax'])
    for i in range(0,source_date_CommodityTax_len,1):
        # 获取每个税额
        print('商品税额'+source_date['words_result']['CommodityTax'][i]['word']+'\n')
    #获取销售方单位名称
    print('销售方单位名称：'+source_date['words_result']['SellerName'])
    #获取发票总金额-数字
    print('总金额-数字'+source_date['words_result']['AmountInFiguers'])
    #获取发票总金额-大写
    print('总金额-大写'+source_date['words_result']['AmountInWords'])
    '''

    '''
     #以下为优化版本
    source_date_CommodityName_len= len(source_date['words_result']['CommodityName'])  
    for i in range(0,source_date_CommodityName_len,1):
        pass
        print('商品名称：'+source_date['words_result']['CommodityName'][i]['word']+'\n')
        print('商品数量：'+source_date['words_result']['CommodityNum'][i]['word']+'\n')
        print('商品单价：'+source_date['words_result']['CommodityPrice'][i]['word']+'\n')
        print('商品金额：'+source_date['words_result']['CommodityAmount'][i]['word']+'\n')
        print('商品税额：'+source_date['words_result']['CommodityTax'][i]['word']+'\n')
    #获取销售方单位名称
    print('销售方单位名称：'+source_date['words_result']['SellerName'])
    #获取发票总金额-数字
    print('总金额-数字'+source_date['words_result']['AmountInFiguers'])
    #获取发票总金额-大写
    print('总金额-大写'+source_date['words_result']['AmountInWords'])
    '''


    #以下为优化版本
    import openpyxl
    workbook = openpyxl.load_workbook('出入库模板.xlsx')
    sheets = workbook.sheetnames
    sheet = workbook[sheets[2]]
    source_date_CommodityName_len= len(source_date['words_result']['CommodityName'])  
    for i in range(0,source_date_CommodityName_len,1):
        print('商品名称：'+source_date['words_result']['CommodityName'][i]['word']+'\n')
        print('商品数量：'+source_date['words_result']['CommodityNum'][i]['word']+'\n')
        print('商品单价：'+source_date['words_result']['CommodityPrice'][i]['word']+'\n')
        print('商品金额：'+source_date['words_result']['CommodityAmount'][i]['word']+'\n')
        print('商品税额：'+source_date['words_result']['CommodityTax'][i]['word']+'\n')
        row_num = i + 11
        sheet['D'+str(row_num)] = source_date['words_result']['CommodityName'][i]['word']
        sheet['G'+str(row_num)] = source_date['words_result']['CommodityNum'][i]['word']
        sheet['H'+str(row_num)] = source_date['words_result']['CommodityNum'][i]['word']
        #单价需要格式化，需要保留3位小数
        sheet['I'+str(row_num)] = f"{float(source_date['words_result']['CommodityPrice'][i]['word']):.3f}"
        #金额 需要进行格式化 需要按照 千、百、十、万、千、百、十、 元、角、分
        
        '''
        思路，拿到的单价必然是小数点后两位
        1、优先判断 是几位数的金额
        '''
        # 获取金额字符串并转换为规范化的两位小数格式
        amount_str = source_date['words_result']['CommodityAmount'][i]['word']
        
        # 直接转换为浮点数并确保两位小数精度
        amount = float(amount_str)
        amount_rounded = round(amount, 2)
        
        # 分离整数和小数部分
        integer_part = int(amount_rounded)
        decimal_part = int(round((amount_rounded - integer_part) * 100))
        
        # 提取整数部分每一位数字
        integer_digits = [int(d) for d in str(integer_part)]
        
        # 提取小数部分每一位数字
        decimal_digits = [(decimal_part // 10) % 10, decimal_part % 10]
        
        # 合并所有数字
        all_digits = integer_digits + decimal_digits
        
        print(f"提取的所有数字: {all_digits}")
        #把小数部分进行填充
        #角
        sheet['R'+str(row_num)] = decimal_digits[0]
        #分
        sheet['S'+str(row_num)] = decimal_digits[1]
        
        # 根据整数位数执行不同逻辑
        digit_count = len(integer_digits)     
        if digit_count == 1:
            # 处理个位金额逻辑
            #all_digits[0]为个位最高位
            sheet['Q'+str(row_num)] = integer_digits[0]
            pass
        elif digit_count == 2:
            # 处理十位金额逻辑
            sheet['P'+str(row_num)] = integer_digits[0]
            sheet['Q'+str(row_num)] = integer_digits[1]
            pass
        elif digit_count == 3:
            # 处理百位金额逻辑
            sheet['O'+str(row_num)] = integer_digits[0]
            sheet['P'+str(row_num)] = integer_digits[1]
            sheet['Q'+str(row_num)] = integer_digits[2]
            pass
        elif digit_count == 4:
            # 处理千位金额逻辑
            sheet['N'+str(row_num)] = integer_digits[0]
            sheet['O'+str(row_num)] = integer_digits[1]
            sheet['P'+str(row_num)] = integer_digits[2]
            sheet['Q'+str(row_num)] = integer_digits[3]
            pass
        elif digit_count == 5:
            # 处理万位金额逻辑
            sheet['M'+str(row_num)] = integer_digits[0]
            sheet['N'+str(row_num)] = integer_digits[1]
            sheet['O'+str(row_num)] = integer_digits[2]
            sheet['P'+str(row_num)] = integer_digits[3]
            sheet['Q'+str(row_num)] = integer_digits[4]
            pass
        elif digit_count == 6:
            # 处理十万位金额逻辑
            sheet['L'+str(row_num)] = integer_digits[0]
            sheet['M'+str(row_num)] = integer_digits[1]
            sheet['N'+str(row_num)] = integer_digits[2]
            sheet['O'+str(row_num)] = integer_digits[3]
            sheet['P'+str(row_num)] = integer_digits[4]
            sheet['Q'+str(row_num)] = integer_digits[5]
            pass
        else:
            print("单价金额过大，请调整程序")


        sheet['T'+str(row_num)] = source_date['words_result']['CommodityTax'][i]['word']
    #获取销售方单位名称
    print('销售方单位名称：'+source_date['words_result']['SellerName'])
    #获取发票总金额-数字
    print('总金额-数字'+source_date['words_result']['AmountInFiguers'])
    sheet['P71'] = source_date['words_result']['AmountInFiguers']
    #获取发票总金额-大写
    print('总金额-大写'+source_date['words_result']['AmountInWords'])
    sheet['E71'] = source_date['words_result']['AmountInWords']
    #获取当前日期
    from datetime import date
    # 获取当前日期
    today = date.today()
    print(f"当前日期: {today.year}年{today.month}月{today.day}日")
    sheet['G8'] = f"当前日期: {today.year}年{today.month}月{today.day}日"


    

    #获取的内容通过表格展现出来
    # 保存修改后的Excel文件（必须执行，否则数据不会写入文件）
    workbook.save('出入库模板_已填充.xlsx')  # 建议另存为新文件，避免覆盖原模板
    print("数据已成功写入Excel文件！")

    


def get_file_content_as_base64(path, urlencoded=False):
    """
    获取文件base64编码
    :param path: 文件路径
    :param urlencoded: 是否对结果进行urlencoded 
    :return: base64编码信息
    """
    with open(path, "rb") as f:
        content = base64.b64encode(f.read()).decode("utf8")
        if urlencoded:
            content = urllib.parse.quote_plus(content)
    return content

def get_access_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))

if __name__ == '__main__':
    main()
